package com.ylb.rent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.ylb.rent.dao.PermissionDao;
import com.ylb.rent.dao.RolePermissionDao;
import com.ylb.rent.entity.Permission;
import com.ylb.rent.entity.RolePermission;
import com.ylb.rent.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/6/28 21:51
 */
@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    PermissionDao permissionDao;

    @Autowired
    RolePermissionDao rolePermissionDao;

    @Override
    public List<Permission> getAll() {
        return permissionDao.selectAll();
    }


    @Override
    public List<Permission> getListByRoleId(long roleId) {

        List<RolePermission> rolePermissions = rolePermissionDao.selectByRoleId(roleId);
        List<Permission> permissions = new ArrayList<>();
        rolePermissions.forEach(item->{
            Permission permission = permissionDao.selectById(item.getPermissionId());
            permissions.add(permission);
        });

        return permissions;
    }

    @Override
    public int insert(Permission permission) {
        return permissionDao.insert(permission);
    }


    public RolePermission getOne(long roleId,long permissionId){
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",roleId).eq("permission_id",permissionId);
        return rolePermissionDao.selectOne(wrapper);

    }


    @Override
    public int updateRolePermission(RolePermission rolePermission) {
        long isDelete = rolePermission.getIsDelete();
        long roleId = rolePermission.getRoleId();
        long permissionId = rolePermission.getPermissionId();
//        如果是要求开启权限
        if(isDelete == 0){
//            查询是否有添加记录
            RolePermission one = this.getOne(roleId,permissionId );

//            如果没有则添加
            if(ObjectUtil.isNull(one)){

                return rolePermissionDao.insert(rolePermission);
            }

        }
//        正常开关权限
        UpdateWrapper<RolePermission> wrapper = new UpdateWrapper<>();
        wrapper.eq("role_id",roleId).eq("permission_id",permissionId);
        return rolePermissionDao.update(rolePermission,wrapper);

    }

    @Override
    public int update(Permission permission) {
        UpdateWrapper<Permission> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",permission.getId());
        return permissionDao.update(permission,wrapper);
    }
}
